package com.itheima.dao;

import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.List;

public class UserMapperImpl {
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Before
    public void before() throws IOException {
        //获取核心配置文件,得到输入流对象
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //构造会话工厂建造类
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        //通过会话工厂建造类得到会话工厂
        SqlSessionFactory factory = factoryBuilder.build(inputStream);
        //通过会话工厂得到会话对象
        sqlSession = factory.openSession();
        //通过会话对象得到UserMapper接口的代理对象
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void after() {
        //提交事务
        sqlSession.commit();
        //关闭事务
        sqlSession.close();
    }

    @Test
    public void selectAll() throws IOException {
        //1. 获取核心配置文件，得到输入流对象
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2. 构造会话工厂建造类
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        //3. 通过建造类得到会话工厂
        SqlSessionFactory factory = factoryBuilder.build(inputStream);
        //4. 通过会话工厂得到会话对象
        SqlSession sqlSession = factory.openSession();
        //5. 通过会话对象得到UserMapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //6. 执行查询操作
        List<User> users = userMapper.selectAll();
        for (User user : users) {
            System.out.println(user);
        }
        //7. 关闭会话
        sqlSession.close();
    }

    @Test
    public void selectById() {
        User user = userMapper.selectById(2);
        System.out.println(user);
    }

    @Test
    public void update() {
        //User user = new User(2, "狐狸精", Date.valueOf("1996-05-10"), "女", "狐狸洞");
        User user = new User(2, "白骨精", Date.valueOf("1992-11-12"), "女", "白虎岭白骨洞");
        int update = userMapper.update(user);
        System.out.println("更新了" + update + "行");
    }

    @Test
    public void deleteById() {
        int delete = userMapper.deleteById(7);
        System.out.println("删除了" + delete + "行");
    }

    @Test
    public void insert() {
        User user = new User(null, "沙悟净", Date.valueOf("1992-11-12"), "男", "流沙河");
        int insert = userMapper.insert(user);
        System.out.println("添加了" + insert + "行");
    }
}
